package org.reliablesource.jdt.model;

import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.JavaModelException;
import org.reliablesource.model.core.IReliableElement;
import org.reliablesource.model.core.ReliableNode;

/**
 * 
 * JavaElementAdapter.java<br>
 * Copyright (c) 2007, Reliable Source, Inc. All Rights Reserved<br>
 * <br>
 * 
 * Created on: May 16, 2007 <br>
 * <br>
 * 
 * @author Dennis Park <a
 *         href="mailto:dennis.park@gmail.com">dennis.park@gmail.com</a>
 * 
 * @since 1.0.0
 */
public class JavaElementAdapter extends ReliableNode {

	protected IJavaElement javaElement;
	/**
	 * 
	 */
	private static final long serialVersionUID = -5208432591171038170L;

	public JavaElementAdapter(IJavaElement _javaElement) {
		javaElement = _javaElement;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.reliablesource.model.core.ReliableElement#hasChildren()
	 */
	@Override
	public boolean hasChildren() {
		if (javaElement instanceof IParent)
			try {
				return ((IParent) javaElement).hasChildren();
			} catch (JavaModelException e) {
				e.printStackTrace();
			}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.reliablesource.model.core.ReliableElement#isRoot()
	 */
	@Override
	public boolean isRoot() {
		if (javaElement instanceof IJavaProject)
			return true;
		return false;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.reliablesource.model.core.IReliableElement#getName()
	 */
	public String getName() {
		return javaElement.getElementName();
	}

	public int getNumLines() {
		IReliableElement[] _elts = getChildren();
		int _nLines = 0;
		for (int i = 0; i < _elts.length; i++) {
			if (javaElement instanceof IPackageFragment)
				_nLines += Integer.parseInt(((SourceElementInfo) _elts[i])
						.getNumLines());
			else
				_nLines += ((JavaElementAdapter) _elts[i]).getNumLines();
		}
		return _nLines;
	}

	public int getNumFiles() {
		if (javaElement instanceof IPackageFragment)
			return getChildren().length;
		else if (javaElement instanceof IJavaProject) {
			IReliableElement[] _elts = getChildren();
			int _nChildren = 0;
			for (int i = 0; i < _elts.length; i++) {
				if (_elts[i] instanceof JavaElementAdapter)
					_nChildren += ((JavaElementAdapter) _elts[i]).getNumFiles();
			}
			return _nChildren;
		}
		return 1;
	}

	public Object getAdaptedObject() {
		return javaElement;
	}
}
